{pkgs, ...}: 
let
  startw = pkgs.writeShellScriptBin "startw" ''
    cd ~
    export XDG_RUNTIME_DIR=/run/user/"$(id -u)"
    timestamp=$(date +%F-%R)
    if [ -z $DISPLAY ]; then
      river -log-level debug > /tmp/river-$timestamp.log 2>&1
    else
      echo "RiverWM is running."
    fi
  '';

  dbus-river-environment = pkgs.writeTextFile {
    name = "dbus-river-environment";
    destination = "/bin/dbus-river-environment";
    executable = true;
    text = ''
      dbus-update-activation-environment --systemd DISPLAY WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE NIXOS_OZONE_WL
      systemctl --user stop pipewire wireplumber xdg-desktop-portal xdg-desktop-portal-wlr
      systemctl --user start pipewire wireplumber xdg-desktop-portal xdg-desktop-portal-wlr
    '';
  };
  
in {
  home.packages = with pkgs; [
    dbus-river-environment
    river
    stacktile
    startw
  ];

  home.sessionVariables = {
    LIBSEAT_BACKEND = "logind";
    GDK_BACKEND = "wayland";
    CLUTTER_BACKEND = "wayland";
    SDL_VIDEODRIVER = "wayland";
    QT_WAYLAND_DISABLE_WINDOWDECORATION = "1";
    _JAVA_AWT_WM_NONREPARENTING = "1";
    XDG_CURRENT_DESKTOP = "river";
    XDG_SESSION_DESKTOP = "wlroots";
    XDG_SESSION_TYPE = "wayland";
  };

  systemd.user.targets.river-session = {
    Unit = {
      Description = "river compositor session";
      BindsTo = ["graphical-session.target"];
      Wants = ["graphical-session-pre.target"];
      After = ["graphical-session-pre.target"];
    };
  };
}
